import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:family_app/src/theme/app_theme.dart';

/// 月份项目组件
/// 显示某一月份的收支概览，支持展开/收起查看详细交易
class MonthItem extends StatefulWidget {
  /// 月份号（1-12）
  final int monthNumber;

  /// 该月收入
  final double income;

  /// 该月支出
  final double expense;

  /// 该月的交易详情列表
  final List<Map<String, dynamic>>? transactions;

  const MonthItem({
    Key? key,
    required this.monthNumber,
    required this.income,
    required this.expense,
    this.transactions,
  }) : super(key: key);

  @override
  State<MonthItem> createState() => _MonthItemState();
}

class _MonthItemState extends State<MonthItem>
    with SingleTickerProviderStateMixin {
  /// 动画控制器
  late AnimationController _controller;

  /// 高度动画
  late Animation<double> _heightAnimation;

  /// 是否展开
  bool isExpanded = false;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    _heightAnimation = Tween<double>(begin: 0, end: 1).animate(
      CurvedAnimation(parent: _controller, curve: Curves.easeInOut),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(bottom: 12.h),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(color: Colors.grey[200]!),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          // 月份头部（可点击展开）
          GestureDetector(
            onTap: _toggleExpanded,
            child: Container(
              padding: EdgeInsets.all(16.w),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    AppTheme.primaryColor.withOpacity(0.05),
                    AppTheme.primaryColor.withOpacity(0.02),
                  ],
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  // 月份号
                  Text(
                    '${widget.monthNumber}月',
                    style: TextStyle(
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w600,
                      color: Colors.black87,
                    ),
                  ),

                  // 收支统计
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 12.w),
                      child: Text(
                        '收入 ¥${widget.income.toStringAsFixed(0)} | 支出 ¥${widget.expense.toStringAsFixed(0)}',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Colors.grey[600],
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),

                  // 展开/收起图标
                  AnimatedRotation(
                    turns: isExpanded ? 0.5 : 0,
                    duration: const Duration(milliseconds: 300),
                    child: Icon(
                      Icons.expand_more,
                      color: AppTheme.primaryColor,
                    ),
                  ),
                ],
              ),
            ),
          ),

          // 展开内容
          ClipRect(
            child: SizeTransition(
              sizeFactor: _heightAnimation,
              child: Container(
                color: Colors.white,
                child: _buildTransactionList(),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建交易列表
  Widget _buildTransactionList() {
    // 如果没有提供交易数据，使用默认示例
    final transactions = widget.transactions ?? _getDefaultTransactions();

    if (transactions.isEmpty) {
      return Padding(
        padding: EdgeInsets.all(16.w),
        child: Center(
          child: Text(
            '该月暂无交易',
            style: TextStyle(
              fontSize: 12.sp,
              color: Colors.grey[400],
            ),
          ),
        ),
      );
    }

    return Column(
      children: List.generate(
        transactions.length,
        (index) => _buildDetailRow(
          transactions[index]['label'] ?? '未知',
          transactions[index]['amount'] ?? 0.0,
          isLast: index == transactions.length - 1,
        ),
      ),
    );
  }

  /// 构建详细交易行
  Widget _buildDetailRow(
    String label,
    double amount, {
    bool isLast = false,
  }) {
    final isIncome = amount > 0;
    final color = isIncome ? Colors.green : Colors.red;

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      decoration: BoxDecoration(
        border: !isLast
            ? Border(
                bottom: BorderSide(color: Colors.grey[100]!),
              )
            : null,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: TextStyle(
              fontSize: 13.sp,
              color: Colors.black87,
            ),
          ),
          Text(
            '${isIncome ? '+' : '-'}¥ ${amount.abs().toStringAsFixed(2)}',
            style: TextStyle(
              fontSize: 13.sp,
              fontWeight: FontWeight.w600,
              color: color,
            ),
          ),
        ],
      ),
    );
  }

  /// 获取默认交易数据（示例）
  List<Map<String, dynamic>> _getDefaultTransactions() {
    return [
      {'label': '餐饮消费', 'amount': -68.50},
      {'label': '购物消费', 'amount': -299.00},
      {'label': '工资收入', 'amount': 8500.00},
    ];
  }

  /// 切换展开/收起状态
  void _toggleExpanded() {
    setState(() => isExpanded = !isExpanded);
    if (isExpanded) {
      _controller.forward();
    } else {
      _controller.reverse();
    }
  }
}
